package com.snb.play.dwebtoon.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import org.json.JSONObject;

import android.util.Log;

public class RESTFulClient {

	private static final String TAG = RESTFulClient.class.getSimpleName();

	private static final int READ_TIME_OUT = 10000;
	private static String ADULTCOOKIE = "";
	private static final String URL_DAUM_WEB_TOON_FORMAT = "http://cartoon.media.daum.net/data/webtoon/list_by_option?genre=&category=&highScore=&minScore=&webtoonStatus=&hotIssue=&page_no=%d&page_size=%d&timestamp=%d";
	private static final String URL_DAUM_WEB_TOON_DETAIL_LIST_FORMAT = "http://m.cartoon.media.daum.net/data/mobile/webtoon/list_episode_by_nickname?nickname=%s&page_no=1&page_size=300&1354606014331=";
	/**
	 * �� url�� ��û�� ���� header ���� �����ص״ٰ�
	 * URL_DAUM_WEB_TOON_VIEW_COMIC_FORMAT ����Ҷ� ���
	 */
//	private static final String URL_DAUM_WEB_TOON_VIEW_COOKIE_FORMAT = "http://cartoon.media.daum.net/webtoon/viewer/%d";
	private static final String URL_DAUM_WEB_TOON_VIEW_COMIC_FORMAT = "http://cartoon.media.daum.net/webtoon/viewer_images.js?webtoon_episode_id=%d";

	public void setAdultLogin(String aCookie) {
		if (ADULTCOOKIE.length() < 1)
			ADULTCOOKIE = aCookie;
	}

	public static boolean isStringDouble(String s) {
		try {
			Double.parseDouble(s);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public int getDaumWebToonCount() {
		int count = 0;

		try {
			URL url = new URL("http://cartoon.media.daum.net/data/webtoon/list_by_option?page_size=0");
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection = initPostHttpURLConnection(httpURLConnection);
			httpURLConnection.connect();
			int status = httpURLConnection.getResponseCode();
			Logger.d(TAG, "status == " + status);
			switch (status) {
				case 200:
				case 201:
					BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
					StringBuilder sb = new StringBuilder();
					String line = br.readLine();
					String[] lines = line.split(":");
					boolean findTotal = false;
					for (String ll : lines) {
						if (findTotal) {
							String lStrCount = ll.split(",")[0].replace("}", "");
							if (isStringDouble(lStrCount)) {
								count = Integer.valueOf(lStrCount);
							}

							break;
						} else if (ll.indexOf("totalItemCount") > -1)
							findTotal = true;
					}
					br.close();
					break;
			}
			httpURLConnection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	public JSONObject getDaumWebToon(int page) throws Exception {
		return getDaumWebToon(page, 40);
	}

	public JSONObject getDaumWebToon(int page, int size) throws Exception {
		JSONObject data = null;
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_FORMAT, page, size, System.currentTimeMillis()));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection = initPostHttpURLConnection(httpURLConnection);
		httpURLConnection.connect();
		int status = httpURLConnection.getResponseCode();

		switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();

				data = new JSONObject(sb.toString());
		}
		httpURLConnection.disconnect();
		return data;
	}

	public JSONObject getDaumWebToonImg(String id) throws Exception {
		JSONObject data = null;
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_VIEW_COMIC_FORMAT, Integer.valueOf(id)));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection = initPostHttpURLConnection(httpURLConnection);
		httpURLConnection.connect();
		int status = httpURLConnection.getResponseCode();

		switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				data = new JSONObject(sb.toString());
		}
		httpURLConnection.disconnect();
		return data;
	}

	public JSONObject getDaumWebToonInfo(String nickName) throws Exception {
		JSONObject data = null;
		Log.d(TAG, String.format(URL_DAUM_WEB_TOON_DETAIL_LIST_FORMAT, nickName));
		URL url = new URL(String.format(URL_DAUM_WEB_TOON_DETAIL_LIST_FORMAT, nickName));
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection = initPostHttpURLConnection(httpURLConnection);
		httpURLConnection.connect();
		int status = httpURLConnection.getResponseCode();

		switch (status) {
			case 200:
			case 201:
				BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				data = new JSONObject(sb.toString());
		}
		httpURLConnection.disconnect();
		return data;
	}

	private HttpURLConnection initPostHttpURLConnection(HttpURLConnection httpURLConnection) throws ProtocolException {
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		if (ADULTCOOKIE.length() > 1) {
			httpURLConnection.setRequestProperty("Cookie", ADULTCOOKIE);
		} else
			httpURLConnection.setRequestProperty("Cookie", "WEBTOON_VIEW=MTAuMTA%3D;VOTE=MTAuMTA%3D;SLOGIN=1");
		return initHttpURLConnection(httpURLConnection);
	}

	private HttpURLConnection initHttpURLConnection(HttpURLConnection httpURLConnection) {
		httpURLConnection.setReadTimeout(READ_TIME_OUT);
		return httpURLConnection;
	}

}
